package com.cn.shrio;



import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.cn.model.User;
import com.cn.service.IUserService;

public class MyRealm extends AuthorizingRealm  {
	@Autowired
	private IUserService userService;
	// 为当前登陆成功的用户授予权限和角色，已经登陆成功了
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principals) {
    	//根据用户名查找拥有的角色  
        /*List<Roles> roles = userService.getUserRoles(userName);  
        if (roles != null) {  
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();  
  
            for (Roles role : roles) {  
                info.addRole(role.getName());  
            }  
  
            return info;  
        } else {  
            return null;  
        }  */
    	return null; 
    }

    // 验证当前登录的用户，获取认证信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal(); // 获取用户名
        User user = userService.getByUsername(username);
        if(user != null) {
            AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(), getName());
            return authcInfo;
        } else {
            return null;
        }       
    }

}
